<template>
  <div class="timeStateBox board-border">
    <div class="typeBox">
      <div class="item" :class="{ active: item.active }" v-for="(item, index) in typeLists" :key="index" @click="clickHandle(item, index)">
        <span>{{ item.label }}</span>
      </div>
    </div>
    <div class="lineBox">
      <NormalLine :lineData="lineData"></NormalLine>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import api from '@api/api';
import { getRoleId, formatArrayToObject } from '@/unit/tool';
// import { RepairType } from '@/unit/constantValue';
import NormalLine from '@components/echart/normalLine';
import { themeOption } from '@components/echart/buildEChartOption';
import '@assets/styles/publicStyle/index.less';

import { createNamespacedHelpers } from 'vuex';
const { mapState } = createNamespacedHelpers('board/');

const typeLists = [
  {
    label: '开机率',
    value: 1,
    active: false,
  },
  {
    label: '运行时间',
    value: 2,
    active: true,
  },
  {
    label: '故障时间',
    value: 3,
    active: false,
  },
];

function buildDateAxis(parames) {
  let { timeFormat, startTime, endTime } = parames;
  // 计算两个日期之间间隔的天数,月数,年数
  let length = 0; //日期跨度变量

  if (timeFormat == 'days') {
    length = moment(endTime).diff(moment(startTime), 'days');
  } else if (timeFormat == 'months') {
    length = moment(endTime).diff(moment(startTime), 'months');
  } else if (timeFormat == 'years') {
    length = moment(endTime).diff(moment(startTime), 'years');
  }

  let xAxis = new Array(length + 1);

  for (let index = 0; index < xAxis.length; index++) {
    if (timeFormat == 'days') {
      xAxis[index] = moment(startTime)
        .add(index, 'days')
        .format('YYYY-MM-DD');
    } else if (timeFormat == 'months') {
      xAxis[index] = moment(startTime)
        .add(index, 'months')
        .format('YYYY-M');
    } else if (timeFormat == 'years') {
      xAxis[index] = moment(startTime)
        .add(index, 'years')
        .format('YYYY');
    }
  }

  return xAxis;
}

function transformTimeArray(lists, lineType) {
  return lists.map((item, index) => {
    return {
      value: [item.day, formatValue(item.yData, lineType)],
    };
  });

  function formatValue(value, lineType) {
    switch (lineType) {
      case 1:
        return (parseFloat(value) * 100).toFixed(2);
      case 2:
        return parseFloat(value / 60).toFixed(2);
      case 3:
        return parseFloat(value / 60).toFixed(2);
      default:
        break;
    }
  }
}

function buildLineLists(lineDatalists, option) {
  let { startTime, endTime, timeFormat, lineType } = option;
  let dataLists = [];
  let legendData = [];
  let xAxisData = buildDateAxis({ timeFormat, startTime, endTime });

  lineDatalists.forEach((item, index) => {
    dataLists.push({
      option: {
        name: item.macsn,
        symbolSize: 4,
        showAllSymbol: true,
      },
      data: transformTimeArray(item.arrayData, lineType),
    });
  });

  legendData = lineDatalists.map((item, index) => {
    let name = item.macsn == '' ? '未知字段' : item.macsn;
    return name;
  });

  return {
    grid: { left: '60', right: '50', top: '20', bottom: '80' },
    tooltip: {
      trigger: 'axis',
      // formatter: (params) => `<p>${params.marker}${params.name}&nbsp;${parseInt(moment.duration(params.value * 1000).asHours())}小时</p>`,
      // formatter: (params) => `<p>${params.marker}${params.name}&nbsp;小时</p>`,
      formatter: (paramsLists) => {
        // console.log(params);
        let str = `<p>${paramsLists[0].value[0]}</p>`;
        switch (lineType) {
          case 1:
            paramsLists.forEach((params, index) => {
              str = str + `<p>${params.marker}${params.seriesName}&nbsp;${params.value[1]}%</p>`;
            });
            return str;
          case 2:
            paramsLists.forEach((params, index) => {
              str = str + `<p>${params.marker}${params.seriesName}&nbsp;${params.value[1]}小时</p>`;
            });
            return str;
          case 3:
            paramsLists.forEach((params, index) => {
              str = str + `<p>${params.marker}${params.seriesName}&nbsp;${params.value[1]}小时</p>`;
            });
            return str;
          default:
            break;
        }
      },
    },
    legend: {
      // orient: 'vertical',
      // left: '10',
      top: '210',
      // icon: 'circle',
      data: legendData,
      // data: [],
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: '#FFFFFF',
      },
      formatter: (params) => {
        return `${params}`;
      },
    },
    yAxis: {
      type: 'value',
      // y 轴线
      axisLine: {
        show: false,
      },
      // 分割线设置
      splitLine: {
        show: true,
        lineStyle: {
          color: '#708ACC',
          width: 0.5,
        },
      },
      //
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          color: '#708ACC',
          fontSize: 14,
        },
      },
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      //
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          color: '#708ACC',
          fontSize: 14,
        },
      },
    },
    dataLists: dataLists,
  };
}

function isDayOrMouth(startTime, endTime) {
  let a = moment(startTime);
  let b = moment(endTime);
  return b.diff(a, 'months') > 0;
}

function formatUrl(value, timeFormat) {
  let isDay = timeFormat == 'days' ? true : false;
  switch (parseInt(value)) {
    // 开机率
    case 1:
      return isDay ? '/GroupOnlineRate.action' : '/HalfYearGroupOnlineRate.action';
    // 运行时间
    case 2:
      return isDay ? '/GroupRunTime.action' : '/HalfYearGroupRunTime.action';
    // 故障时间
    case 3:
      return isDay ? '/GroupAlarmTime.action' : '/HalfYearGroupAlarmTime.action';
    default:
      break;
  }
}

export default {
  name: 'timeState',
  components: {
    NormalLine,
  },
  props: {},
  data() {
    return {
      userName: '',
      name: '',
      role: '',
      compId: '',
      lineData: {},
      typeLists,
      startTime: '',
      endTime: '',
      timeFormat: '',
      lineType: typeLists.findIndex((item) => item.active) + 1,
    };
  },
  watch: {
    timeSwich: function(newValue, oldValue) {
      let { startTime, endTime } = newValue;
      let isMouth = isDayOrMouth(startTime, endTime);
      let timeFormat = isMouth ? 'months' : 'days';
      this.startTime = startTime;
      this.endTime = endTime;
      this.timeFormat = timeFormat;
      this.getData({ startTime, endTime, timeFormat, lineType: this.lineType });
    },
  },
  computed: {
    ...mapState(['timeSwich']),
  },
  methods: {
    //
    clickHandle(item, index) {
      let { value, active } = item;
      this.lineType = value;
      this.typeLists.forEach((obj, i) => {
        if (index == i) {
          obj.active = true;
        } else {
          obj.active = false;
        }
      });
      this.getData({ startTime: this.startTime, endTime: this.endTime, timeFormat: this.timeFormat, lineType: this.lineType });
    },
    //
    getData(parames) {
      let { timeFormat } = parames;
      this.typeLists.forEach((item, index) => {
        if (item.active) {
          // this.boardDayProduceSum(parames, 'lineData', timeFormat);
          this.boardTimeState(formatUrl(item.value, timeFormat), parames, 'lineData');
        }
      });
    },
    //
    async boardTimeState(url, parames, key) {
      let { startTime, endTime, timeFormat, lineType } = parames;
      const resData = await api.boardTimeState(url, { UserName: this.userName, compid: this.compId, startTime, endTime });

      let dataLists = [];
      let timeOption = {
        startTime,
        endTime,
        timeFormat,
        lineType,
      };

      this[key] = buildLineLists(resData, timeOption);
    },
  },
  created() {},
  mounted() {
    getRoleId(this);
  },
};
</script>

<style scoped="scoped" lang="less">
@import './style.less';
</style>
